<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏房间</title>
    <style>
        /* 基础样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }

        body {
            background-image: url('../image/reg_back.jpg');
            background-repeat: no-repeat;
            background-position: center;
            background-size: cover;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            overflow-x: hidden;
        }

        .nav {
            height: 115px;
            /* 增加高度 */
            background: linear-gradient(to bottom, #0387fa 60%, #39b0f5 100%);
            /* 渐变背景 */
            color: white;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;
            position: sticky;
            top: 0;
            z-index: 100;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
        }

        .player-info {
            display: flex;
            flex-direction: column;
            align-items: center;
            flex: 1;
            padding: 10px;
            min-width: 0;
            position: relative;
        }

        .player-name-team {
            font-weight: bold;
            font-size: 16px;
            margin-bottom: 8px;
            text-align: center;
        }

        .player-name-value {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
            text-align: center;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 100%;
        }

        .player-stats-container {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .player-stats {
            display: flex;
            gap: 20px;
            font-size: 14px;
        }

        .stat-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            min-width: 70px;
        }

        .stats-label {
            opacity: 0.8;
            font-size: 14px;
            margin-bottom: 5px;
        }

        .stats-value {
            font-weight: bold;
            font-size: 24px;
            /* 加大数字 */
            line-height: 1.2;
        }

        .vs-divider {
            font-size: 32px;
            /* 加大VS字号 */
            font-weight: bold;
            padding: 0 10px;
            text-shadow: 0 0 5px rgba(255, 255, 255, 0.5);
        }

        /* 添加灰色背景带 */
        .player-info::before {
            content: "";
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 50px;
            background-color: rgba(50, 50, 50, 0.7);
            z-index: -1;
            transform: translateY(-50%);
            border-radius: 5px;
        }

        .container {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
            position: relative;
        }

        /* 认输按钮 */
        #defeat_button {
            background: linear-gradient(to right, #ff4d4d, #cc0000);
            /* 红色渐变 */
            margin-top: 10px;
        }

        /* 棋盘区域 */
        #chess_area {
            width: 100%;
            max-width: 500px;
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-bottom: 20px;
            position: relative;
        }

        #chess {
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: 10px;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }

        #screen {
            width: 100%;
            height: 50px;
            margin-top: 15px;
            background-color: rgba(240, 240, 240, 0.8);
            font-size: 20px;
            line-height: 50px;
            text-align: center;
            border-radius: 8px;
            font-weight: bold;
            color: #333;
        }

        /* 聊天框系统 - 向上展开 */
        .chat-container {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            z-index: 200;
            transition: transform 0.4s ease;
            transform: translateY(100%);
            max-width: 800px;
            margin: 0 auto;
        }

        .chat-container.expanded {
            transform: translateY(0);
        }

        .chat-toggle {
            position: absolute;
            top: -40px;
            left: 50%;
            transform: translateX(-50%);
            background-color: #3498db;
            color: white;
            padding: 10px 25px;
            border-radius: 20px 20px 0 0;
            cursor: pointer;
            box-shadow: 0 -3px 10px rgba(0, 0, 0, 0.1);
            font-size: 16px;
            z-index: 201;
        }

        .chat-toggle:hover {
            background-color: #2980b9;
        }

        .chat-toggle::after {
            content: "▲";
            margin-left: 10px;
            transition: transform 0.3s ease;
        }

        .chat-container.expanded .chat-toggle::after {
            transform: rotate(180deg);
        }

        .chat-content {
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 15px 15px 0 0;
            box-shadow: 0 -5px 20px rgba(0, 0, 0, 0.2);
            padding: 15px;
            height: 300px;
            display: flex;
            flex-direction: column;
        }

        #chat_show {
            flex: 1;
            padding: 15px;
            overflow-y: auto;
            background-color: #f9f9f9;
            border-radius: 8px;
            margin-bottom: 10px;
            display: flex;
            flex-direction: column;
        }

        .chat-message {
            padding: 10px 15px;
            margin: 8px 0;
            border-radius: 15px;
            max-width: 80%;
            word-wrap: break-word;
            font-size: 16px;
            line-height: 1.4;
        }

        .self-message {
            background-color: #d1e7dd;
            align-self: flex-end;
            border-bottom-right-radius: 5px;
            border: 1px solid #bcd0c7;
        }

        .peer-message {
            background-color: #cfe2ff;
            align-self: flex-start;
            border-bottom-left-radius: 5px;
            border: 1px solid #b8cef9;
        }

        .chat-input-area {
            display: flex;
            gap: 10px;
        }

        #chat_input {
            flex: 1;
            height: 45px;
            padding: 0 15px;
            font-size: 16px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background-color: #f9f9f9;
        }

        #chat_button {
            width: 90px;
            height: 45px;
            background-color: #27ae60;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
            font-weight: bold;
        }

        #chat_button:hover {
            background-color: #219653;
        }

        #chat_button:active {
            background-color: #1e8449;
            transform: translateY(1px);
        }

        /* 响应式设计 */
        @media (max-width: 600px) {
            #chess {
                width: 95vw;
                height: 95vw;
            }

            #screen {
                font-size: 18px;
            }

            .chat-content {
                height: 250px;
            }

            .chat-toggle {
                font-size: 14px;
                padding: 8px 20px;
                top: -35px;
            }

            .nav {
                font-size: 14px;
                height: auto;
                min-height: 70px;
                line-height: 1.4;
                padding-top: 5px;
                padding-bottom: 5px;
            }

            .player-name {
                font-weight: bold;
                font-size: 18px;
                margin-bottom: 3px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                max-width: 100%;
            }

            .player-stats {
                gap: 8px;
                font-size: 12px;
            }

            .stats-value {
                font-size: 14px;
            }

            .vs-divider {
                font-size: 16px;
            }
        }

        @media (max-width: 400px) {
            .player-stats {
                flex-direction: column;
                gap: 2px;
            }

            .player-stats span {
                flex-direction: row;
                gap: 5px;
            }
        }

        /* 浮动弹窗样式*/
        .top-message {
            position: fixed;
            top: 80px;
            left: 50%;
            transform: translateX(-50%);
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 15px 30px;
            border-radius: 30px;
            z-index: 1000;
            max-width: 90%;
            text-align: center;
            animation: fadeInOut 2s forwards;
            /* 持续时间为1秒 */
            font-size: 18px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
        }

        /* 对方消息提示样式 */
        .peer-notification {
            background-color: #3498db;
            /* 蓝色背景区分 */
            top: 120px;
            /* 位于常规提示下方 */
        }

        @keyframes fadeInOut {
            0% {
                opacity: 0;
                transform: translateX(-50%) translateY(-20px);
            }

            20% {
                opacity: 1;
                transform: translateX(-50%) translateY(0);
            }

            80% {
                opacity: 1;
                transform: translateX(-50%) translateY(0);
            }

            100% {
                opacity: 0;
                transform: translateX(-50%) translateY(-20px);
            }
        }

        /* 返回大厅按钮 */
        .action-button {
            display: block;
            width: 100%;
            max-width: 300px;
            height: 60px;
            margin: 20px auto;
            background: linear-gradient(to right, #ff8a00, #da1b60);
            color: white;
            border: none;
            border-radius: 30px;
            font-size: 22px;
            font-weight: bold;
            cursor: pointer;
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.3);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            z-index: 50;
        }

        .action-button:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4);
        }

        .action-button:active {
            transform: translateY(1px);
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);
        }

        .action-button::after {
            content: '';
            position: absolute;
            top: -50%;
            left: -60%;
            width: 20px;
            height: 200%;
            background: rgba(255, 255, 255, 0.3);
            transform: rotate(30deg);
            transition: all 0.6s;
        }

        .action-button:hover::after {
            left: 120%;
        }

        /* 棋盘禁用覆盖层 - 仅覆盖棋盘区域 */
        .chess-disabled-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.01);
            z-index: 100;
            cursor: not-allowed;
            display: none;
        }
    </style>
</head>

<body>
    <!-- 导航栏，显示玩家信息 -->
    <div class="nav">
        <div class="player-info" id="white-player">
            <div class="player-name-team">白方</div>
            <div class="player-stats-container">
                <div class="player-name-value" id="white_name">等待中...</div>
                <div class="player-stats">
                    <span class="stat-item">
                        <div class="stats-label">得分</div>
                        <div class="stats-value" id="white_score">0</div>
                    </span>
                    <span class="stat-item">
                        <div class="stats-label">胜场</div>
                        <div class="stats-value" id="white_win">0</div>
                    </span>
                </div>
            </div>
        </div>

        <div class="vs-divider">VS</div>

        <div class="player-info" id="black-player">
            <div class="player-name-team">黑方</div>
            <div class="player-stats-container">
                <div class="player-name-value" id="black_name">等待中...</div>
                <div class="player-stats">
                    <span class="stat-item">
                        <div class="stats-label">得分</div>
                        <div class="stats-value" id="black_score">0</div>
                    </span>
                    <span class="stat-item">
                        <div class="stats-label">胜场</div>
                        <div class="stats-value" id="black_win">0</div>
                    </span>
                </div>
            </div>
        </div>
    </div>
    <div class="container">
        <div id="chess_area">
            <div style="position:relative">
                <canvas id="chess" width="450px" height="450px"></canvas>
                <div class="chess-disabled-overlay" id="chessOverlay"></div>
            </div>
            <div id="screen">轮到对方走棋...</div>
            <button id="defeat_button" class="action-button">认输</button>
        </div>
    </div>

    <!-- 聊天框容器 - 固定在底部 -->
    <div class="chat-container" id="chat_container">
        <div class="chat-toggle" id="chat_toggle">展开聊天框</div>
        <div class="chat-content">
            <div id="chat_show">
                <div class="chat-message peer-message">你好！</div>
                <div class="chat-message self-message">你好！</div>
            </div>
            <div class="chat-input-area">
                <input type="text" id="chat_input" placeholder="输入聊天内容">
                <button id="chat_button">发送</button>
            </div>
        </div>
    </div>

    <script>
        // 全局变量声明
        let chessBoard = [];
        const BOARD_ROW_AND_COL = 15;
        let chess, context;
        let gameOver = false;
        let ws_url, ws_hdl;
        let room_info = null;
        let is_me;

        // 显示浮动消息（顶部提示）
        function showTopMessage(message, isPeerNotification = false) {
            const msg = document.createElement('div');
            msg.className = `top-message ${isPeerNotification ? 'peer-notification' : ''}`;
            msg.textContent = message;
            document.body.appendChild(msg);

            setTimeout(() => {
                if (document.body.contains(msg)) {
                    document.body.removeChild(msg);
                }
            }, 2000);
        }

        // 专用对方消息提示函数
        function showPeerMessage(message) {
            showTopMessage(message, true);
        }

        // 禁用棋盘点击
        function disableChessClick() {
            document.getElementById('chessOverlay').style.display = 'block';
        }

        // 启用棋盘点击
        function enableChessClick() {
            document.getElementById('chessOverlay').style.display = 'none';
        }

        function initGame() {
            chess = document.getElementById('chess');
            context = chess.getContext('2d');
            initBoard();
            context.strokeStyle = "#8B4513";

            // 棋盘背景
            let logo = new Image();
            logo.src = "image/play_back.jpg";
            logo.onload = function () {
                context.drawImage(logo, 0, 0, 450, 450);
                drawChessBoard();
            }
        }

        function initBoard() {
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                chessBoard[i] = [];
                for (let j = 0; j < BOARD_ROW_AND_COL; j++) {
                    chessBoard[i][j] = 0;
                }
            }
        }

        function drawChessBoard() {
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                context.beginPath();
                context.moveTo(15 + i * 30, 15);
                context.lineTo(15 + i * 30, 435);
                context.stroke();
                context.beginPath();
                context.moveTo(15, 15 + i * 30);
                context.lineTo(435, 15 + i * 30);
                context.stroke();
            }
        }

        function oneStep(i, j, isWhite) {
            if (i < 0 || j < 0) return;
            context.beginPath();
            context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
            context.closePath();
            var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
            if (!isWhite) {
                gradient.addColorStop(0, "#0A0A0A");
                gradient.addColorStop(1, "#636766");
            } else {
                gradient.addColorStop(0, "#D1D1D1");
                gradient.addColorStop(1, "#F9F9F9");
            }
            context.fillStyle = gradient;
            context.fill();
        }

        // 设置棋盘事件监听
        function setupChessEventListeners() {
            const chessElement = document.getElementById('chess');
            chessElement.addEventListener('click', handleChessInteraction);
            chessElement.addEventListener('touchend', handleChessInteraction);
        }

        function handleChessInteraction(e) {
            if (e.type === 'touchend') {
                e.preventDefault();
            }

            if (gameOver || !is_me) {
                if (!is_me) {
                    showTopMessage("等待对方走棋...");
                }
                return;
            }

            const rect = chess.getBoundingClientRect();
            const scaleX = chess.width / rect.width;
            const scaleY = chess.height / rect.height;

            let clientX, clientY;

            if (e.type === 'touchend') {
                const touch = e.changedTouches[0];
                clientX = touch.clientX;
                clientY = touch.clientY;
            } else {
                clientX = e.clientX;
                clientY = e.clientY;
            }

            const x = (clientX - rect.left) * scaleX;
            const y = (clientY - rect.top) * scaleY;
            const col = Math.floor(x / 30);
            const row = Math.floor(y / 30);

            if (row < 0 || row >= BOARD_ROW_AND_COL || col < 0 || col >= BOARD_ROW_AND_COL) {
                return;
            }

            if (chessBoard[row][col] != 0) {
                showTopMessage("当前位置已有棋子！");
                return;
            }

            send_chess(row, col);
        }

        function send_chess(r, c) {
            var chess_info = {
                optype: "put_chess",
                room_id: room_info.room_id,
                uid: room_info.uid,
                row: r,
                col: c
            };
            ws_hdl.send(JSON.stringify(chess_info));
        }

        function set_screen(me) {
            var screen_div = document.getElementById("screen");
            if (me) {
                screen_div.innerHTML = "轮到己方走棋...";
            } else {
                screen_div.innerHTML = "轮到对方走棋...";
            }
        }

        // 更新玩家信息显示
        function updatePlayerInfo() {
            document.getElementById('white_name').textContent = room_info.white_name;
            document.getElementById('white_score').textContent = room_info.white_score;
            document.getElementById('white_win').textContent = room_info.white_win;

            document.getElementById('black_name').textContent = room_info.black_name;
            document.getElementById('black_score').textContent = room_info.black_score;
            document.getElementById('black_win').textContent = room_info.black_win;
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function () {
            // 初始化游戏元素
            initGame();
            setupChessEventListeners();

            // 初始化WebSocket连接
            ws_url = "wss://" + location.host + "/room";
            ws_hdl = new WebSocket(ws_url);

            // 断开连接处理
            window.addEventListener('pagehide', (event) => {
                if (event.persisted === false && ws_hdl) {
                    ws_hdl.close(1005);
                    ws_hdl = null;
                }
            });

            document.addEventListener('visibilitychange', () => {
                if (document.visibilityState === 'hidden') {
                    console.log("页面隐藏，连接保持");
                }
            });

            // WebSocket事件处理
            ws_hdl.onopen = function () {
                console.log("房间长连接建立成功");
                showTopMessage('游戏房间连接成功！');
            }

            ws_hdl.onclose = function () {
                console.log("房间长连接断开");
            }

            ws_hdl.onerror = function () {
                console.log("房间长连接出错");
                showTopMessage('网络连接错误');
            }

            ws_hdl.onmessage = function (evt) {
                var info = JSON.parse(evt.data);
                console.log(JSON.stringify(info));

                if (info.optype == "room_ready") {
                    room_info = info;
                    is_me = room_info.uid == room_info.black_id;//黑方先手
                    set_screen(is_me);
                    updatePlayerInfo();
                } else if (info.optype == "put_chess") {
                    if (info.result == false) {
                        showTopMessage(info.reason);
                        return;
                    }

                    is_me = info.uid == room_info.uid ? false : true;
                    set_screen(is_me);

                    const isWhite = info.uid == room_info.white_id;
                    if (info.row != -1 && info.col != -1) {
                        oneStep(info.col, info.row, isWhite);
                        chessBoard[info.row][info.col] = 1;
                    }

                    if (info.winner > 0) {
                        gameOver = true;
                        disableChessClick();

                        var screen_div = document.getElementById("screen");
                        if (room_info.uid == info.winner) {
                            screen_div.innerHTML = "恭喜你获胜了！";
                            showTopMessage('你赢了！');
                        } else {
                            screen_div.innerHTML = "很遗憾，你输了";
                            showTopMessage('游戏结束，你输了');
                        }

                        updatePlayerInfo();

                        var button_div = document.createElement("button");
                        button_div.className = "action-button";
                        button_div.innerHTML = "返回大厅";
                        button_div.onclick = function () {
                            location.replace("/game_hall.html");
                            ws_hdl.close(1005);
                        }

                        var chess_area_div = document.getElementById("chess_area");
                        var existingButton = chess_area_div.querySelector('.action-button');
                        if (existingButton) {
                            chess_area_div.removeChild(existingButton);
                        }
                        chess_area_div.appendChild(button_div);
                    }

                    if (info.reason && info.reason.includes("对方掉线")) {
                        showTopMessage("对方离开房间，你赢了！");
                    }
                } else if (info.optype == "chat") {
                    if (info.result == false) {
                        showTopMessage(info.reason);
                        return;
                    }

                    if (info.uid != room_info.uid) {
                        showPeerMessage("对方发送消息！");
                    }

                    var msg_div = document.createElement("div");
                    msg_div.className = "chat-message";
                    msg_div.innerHTML = info.message;

                    if (info.uid == room_info.uid) {
                        msg_div.classList.add("self-message");
                    } else {
                        msg_div.classList.add("peer-message");
                    }

                    var msg_show_div = document.getElementById("chat_show");
                    msg_show_div.appendChild(msg_div);
                    msg_show_div.scrollTop = msg_show_div.scrollHeight;
                } else if (info.optype == "admit_defeat") {
                    is_me = info.uid == room_info.uid ? false : true;
                    set_screen(is_me);
                    gameOver = true;
                    disableChessClick();
                    var screen_div = document.getElementById("screen");
                    if (room_info.uid == info.winner) {
                        screen_div.innerHTML = "对方认输，你赢了！";
                        showTopMessage('对方认输,你赢了！');
                    } else {
                        screen_div.innerHTML = "很遗憾，你输了";
                        showTopMessage('很遗憾，你输了');
                    }
                    var button_div = document.createElement("button");
                    button_div.className = "action-button";
                    button_div.innerHTML = "返回大厅";
                    button_div.onclick = function () {
                        location.replace("/game_hall.html");
                        ws_hdl.close(1005);
                    }

                    var chess_area_div = document.getElementById("chess_area");
                    var existingButton = chess_area_div.querySelector('.action-button');
                    if (existingButton) {
                        chess_area_div.removeChild(existingButton);
                    }
                    chess_area_div.appendChild(button_div);
                }
            }

            // 聊天框切换逻辑
            const chatContainer = document.getElementById('chat_container');
            const chatToggle = document.getElementById('chat_toggle');

            chatToggle.addEventListener('click', () => {
                chatContainer.classList.toggle('expanded');
                chatToggle.textContent = chatContainer.classList.contains('expanded')
                    ? '隐藏聊天框'
                    : '展开聊天框';
            });

            // 聊天按钮事件
            document.getElementById("chat_button").onclick = function () {
                var message = document.getElementById("chat_input").value;
                if (!message.trim()) {
                    showTopMessage('消息不能为空');
                    return;
                }

                var send_msg = {
                    optype: "chat",
                    room_id: room_info ? room_info.room_id : "",
                    uid: room_info ? room_info.uid : "",
                    message: message
                };
                ws_hdl.send(JSON.stringify(send_msg));
                document.getElementById("chat_input").value = "";
            }

            // 回车发送消息
            document.getElementById("chat_input").addEventListener("keypress", function (e) {
                if (e.key === "Enter") {
                    document.getElementById("chat_button").click();
                }
            });

            // 认输按钮事件
            document.getElementById("defeat_button").onclick = function () {
                if (!room_info) {
                    showTopMessage("尚未进入游戏房间");
                    return;
                }

                if (gameOver) {
                    showTopMessage("游戏已结束");
                    return;
                }

                if (!is_me) {
                    showTopMessage("现在不是你的回合");
                    return;
                }

                var defeat_info = {
                    optype: "admit_defeat",
                    room_id: room_info.room_id,
                    uid: room_info.uid,
                };
                ws_hdl.send(JSON.stringify(defeat_info));

                this.disabled = true;
                setTimeout(() => { this.disabled = false; }, 2000);
            };
        });
    </script>